package controller;

import entity.User;
import service.UserService;
import util.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginController extends HttpServlet {
    private UserService us = new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cookie = CookieUtils.getCookieValue(req, "admin");
        if (cookie != null&& !cookie.equals("")) {
            String[] split = cookie.split(":");
            req.setAttribute("username",split[0]);
            req.setAttribute("password",split[1]);
            req.setAttribute("isRemember",true);
        }


        req.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String vcode = req.getParameter("vcode");
        String isRemember = req.getParameter("isRemember");
        boolean flag = isRemember == null ? true : false;
        if (flag){
            CookieUtils.deleteCookie(req,resp,"admin");
        }
        HttpSession session = req.getSession();
        String code = (String)session.getAttribute("code");
        if(vcode.equalsIgnoreCase(code)){
            User u = us.login(username,password);
            if(u != null){
                if(!flag){
                    CookieUtils.setCookie(req,resp,"admin",String.format("%s:%s",username,password),60*60*24*7);
                }
                session.setAttribute("user",u);
                req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req, resp);
            }else {
                session.setAttribute("message","账号或者密码错误");
                resp.sendRedirect("/login");
            }
        }else {
            session.setAttribute("message","验证码错误");
            resp.sendRedirect("/login");
        }

    }
}
